enum siteCategory {
    game,
    value
}

/**常用漏斗点位(如果是游戏站此处则归并为常用点位) */
export enum funnelAction {
    g_engine_start = "g_engine_start",
    g_engine_loaded = "g_engine_loaded",
    g_game_loaded = "g_game_loaded",
    g_game_playing = "g_game_playing",
    g_gaming_first_touch = "g_gaming_first_touch",
    g_start_button_click = "g_start_button_click"
}

/**常用点位 */
export enum usuallyAction {
    g_engine_start = "g_engine_start ",
    g_game_pass = "g_game_pass",
    g_button_next_auto_click = "g_button_next_auto_click",
    g_button_next_click = "g_button_next_click",
    plus_game_pass = "plus_game_pass",
    plus_game_icon = "plus_game_icon"
}

/**不常用点位 */
export enum customizeAction {
    g_game_show = "g_game_show",
    g_question_number_ = "g_question_number_",
    g_play_other_icon_click = "g_play_other_icon_click",
    g_button_again_click = "g_button_again_click ",
    g_timeEnd_jump = "g_timeEnd_jump",
    g_correct_jump = "g_correct_jump",
    g_error_jump = "g_error_jump",
}

type Action = funnelAction | usuallyAction | customizeAction | string
export class Track {
    private static _instance: Track = null
    private curGameCategory: siteCategory
    private gameId: any
    private gameModule: string
    private onceActionMap: Map<Action, number> = new Map()
    private TrackStack = []
    private log: boolean = false
    static get Ins() {
        if (!this._instance) {
            this._instance = new this()
        }
        return this._instance
    }

    init(isDev: boolean, gameModule?: string) {
        if (isDev) {
            this.changeLog(true)
            window['parent']["gtag"] = () => { }
            window['parent']["gtag_t"] = () => { }
        }
        if (!window.parent || window.parent["gtag"] === undefined) {
            console.warn("gtag no find!")
            return
        }
        if (this.init.prototype.flag) {
            console.warn("already initialized!")
            return
        }
        this.init.prototype.flag = true
        if (gameModule !== undefined) {
            this.curGameCategory = siteCategory.game
            this.gameModule = gameModule
        } else {
            this.curGameCategory = siteCategory.value
            this.gameId = window.parent["gameId"]
        }
    }

    GA(action: Action, isOnce: boolean = false) {
        if (!this.init.prototype.flag) {
            console.warn("initialization failed!")
            return
        }

        if (isOnce) {
            if (this.onceActionMap.has(action)) {
                return
            } else {
                this.onceActionMap.set(action, 1)
            }
        }

        if (this.curGameCategory === siteCategory.value) {
            if (action in funnelAction) {
                window.parent["gtag_t"](action, `content_${this.gameId}`);
            } else {
                window.parent["gtag"]("event", action, {
                    event_category: `content_${this.gameId}`,
                })
            }
        } else {
            window.parent["gtag"]("event", action, {
                event_category: this.gameModule,
            });
        }

        if (this.log) {
            if (this.curGameCategory === siteCategory.value) {
                console.log(`%c gameId-->${this.gameId};action-->${action};isOnce-->${isOnce}`, 'color:green');

            } else {
                console.log(`%c gameModule-->${this.gameModule};action-->${action};isOnce-->${isOnce}`, 'color:green');
            }
        }

        this.TrackStack.push({
            action,
            isOnce,
            caller: Function.prototype.caller.call(this.GA)
        })
    }

    /**
     * 
     * @param prtCaller 是否打印调用的函数
     */
    consoleTrackStack(prtCaller: boolean = false) {
        let actionMap = new Map()
        this.TrackStack.forEach((value, idx) => {
            let curNum = actionMap.get(value.action)
            if (curNum) {
                actionMap.set(value.action, ++curNum)
            } else {
                actionMap.set(value.action, 1)
            }
            console.log(`%c ${idx + 1}:action=>${value.action} ----- isOnce=>${value.isOnce}${prtCaller ? ' ----- caller=>' : ''}`, 'color:blue', prtCaller ? value.caller : '');
        })
        for (const [key, val] of actionMap) {
            console.log(`%c ${key} =====total=====> ${val}`, 'color:blue');
        }
    }

    changeLog(flag: boolean) {
        this.log = flag
    }

    //---------------------以下为游戏站专有方法----------------------------------
    isHaveGameNext() {
        return window.parent && window.parent["gameNext"]
    }

    /**游戏站重玩跳转按钮打点方法 */
    dpJump(isToNextGame = false) {
        this.GA(usuallyAction.plus_game_pass, true)
        if (isToNextGame && window.parent && window.parent["nextGameFn"]) {
            window.parent["nextGameFn"]()
        } else {
            window.parent.location.reload();
        }
    }

    /**游戏站判断是否自动跳转下一个游戏 */
    autoToNextGame(nextNode: cc.Node, times: number = 2) {
        if (Track.Ins.isHaveGameNext()) {
            nextNode.active = true
            cc.Canvas.instance.scheduleOnce(() => {
                this.GA(usuallyAction.g_button_next_auto_click, true)
                this.dpJump(true)
            }, times)
        }
    }

    /**游戏站暂停方法 */
    addPauseEvent() {
        if (CC_BUILD && !location.href.includes('game.sp.com')) {
            window.addEventListener("showGame", () => {
                console.log('resume');
                cc.director.resume()
                window['ShowGameFlag'] = true
            }, false);

            if (!window['ShowGameFlag']) {
                console.log('pause');
                cc.director.pause()
                window["gameLoaded"] = true;
                window.dispatchEvent(new CustomEvent("gameLoaded"));
            }
        }
        if (!CC_BUILD || location.href.includes('game.sp.com')) {
            window.parent["gameNext"] = true
        }
    }
    //---------------------以下为内容站专有方法----------------------------------
}